// pages/search/result.ts
import { createStoreBindings } from 'mobx-miniprogram-bindings'
import { store } from "~/stores/app"
import { doList, doAddPhoneLog } from '~/api/search'
import * as watch from '~/utils/watch'
import { timeFrom } from '~/utils/util'
import { queryFormState } from '~/../typings/types/result'
import type { itemState } from '~/../typings/types/city'
let isRefresh = false
Page({

  /**
   * 页面的初始数据
   */
  data: {
    title: '' as string,
    queryForm: {
      pageNo: 1,
      pageSize: 10,
      sourceProvince: '',
      sourceCity: '',
      sourceArea: '',
      destProvince: '',
      destCity: '',
      destArea: ''
    } as queryFormState,
    status: 'loading' as 'loading' | 'loadmore' | 'nomore',
    tableData: [] as any[],
    dialogKey: '' as string,
  },
  handMusic(this: any) {
    this.dialog.open()
  },
  searchChange(e: any) {
    const info = {
      star: '',
      end: ''
    }
    this.setSearch(info)
    const item: {
      star: string
      end: string
    } = e
    const starArr = item.star.split('-')
    const endArr = item.end.split('-')
    if (['北京', '重庆', '天津', '上海'].includes(starArr[0])) {
      starArr.splice(1, 1, starArr[0])
    }
    if (['北京', '重庆', '天津', '上海'].includes(endArr[0])) {
      endArr.splice(1, 1, endArr[0])
    }
    const { queryForm } = this.data
    queryForm.sourceProvince = ''
    queryForm.sourceCity = ''
    queryForm.sourceArea = ''
    queryForm.destProvince = ''
    queryForm.destCity = ''
    queryForm.destArea = ''
    if (starArr.length >= 1) {
      queryForm.sourceProvince = starArr[0]
    }
    if (starArr.length >= 2) {
      queryForm.sourceCity = starArr[1]
    }
    if (starArr.length >= 3) {
      queryForm.sourceArea = starArr[2]
    }
    if (endArr.length >= 1) {
      queryForm.destProvince = endArr[0]
    }
    if (endArr.length >= 2) {
      queryForm.destCity = endArr[1]
    }
    if (endArr.length >= 3) {
      queryForm.destArea = endArr[2]
    }
    let dialog = this.dialog
    dialog.close()  // 调用自定义组件中的方法
    this.setData({
      queryForm
    })
    this.setTitle()
    this.refres()
  },
  handStarCity() {
    const { queryForm } = this.data
    wx.navigateTo({
      url: '/pages/city/index?type=star',
      events: {
        chooseEvent: (e: itemState[]) => {
          queryForm.sourceProvince = ''
          queryForm.sourceCity = ''
          queryForm.sourceArea = ''
          if (e.length >= 1) {
            queryForm.sourceProvince = e[0].label
          }
          if (e.length >= 2) {
            if (['北京', '重庆', '天津', '上海'].includes(e[0].label)) {
              queryForm.sourceCity = e[0].label
            } else {
              queryForm.sourceCity = e[1].label
            }
          }
          if (e.length >= 3) {
            queryForm.sourceArea = e[2].label
          }
          this.setData({
            queryForm
          })
          this.refres()
          this.setTitle()
        }
      }
    })
  },
  handEndCity() {
    const { queryForm } = this.data
    wx.navigateTo({
      url: '/pages/city/index?type=end',
      events: {
        chooseEvent: (e: itemState[]) => {
          queryForm.destProvince = ''
          queryForm.destCity = ''
          queryForm.destArea = ''
          if (e.length >= 1) {
            queryForm.destProvince = e[0].label
          }
          if (e.length >= 2) {
            if (['北京', '重庆', '天津', '上海'].includes(e[0].label)) {
              queryForm.destCity = e[0].label
            } else {
              queryForm.destCity = e[1].label
            }
          }
          if (e.length >= 3) {
            queryForm.destArea = e[2].label
          }
          this.setData({
            queryForm
          })
          this.refres()
          this.setTitle()
        }
      }
    })
  },
  handCall(e: any) {
    const dataset = e.currentTarget.dataset
    const { tableData } = this.data
    const info = tableData.find((el) => el.id == dataset.id)
    if (info.mobile) {
      doAddPhoneLog({
        id: info.id,
        type: 2
      })
      const phones = info.mobile.split(' ').filter((el: string) => !!el)
      if (phones.length > 0) {
        wx.makePhoneCall({
          phoneNumber: phones[0]
        })
      }
    }
  },
  handOrder() {
    wx.switchTab({
      url: '/pages/tabbar/order/index'
    })
  },
  handDetail(e: any) {
    const dataset = e.currentTarget.dataset
    wx.navigateTo({
      url: `/pages/shop/detail/detail?id=${dataset.id}`
    })
  },
  setTitle() {
    const { queryForm } = this.data
    const star = queryForm.sourceArea || queryForm.sourceCity || queryForm.sourceProvince
    const end = queryForm.destArea || queryForm.destCity || queryForm.destProvince
    this.setData({
      title: `${star}-${end}`
    })
  },
  /**
   * 分页获取数据
   */
  refres() {
    const { queryForm } = this.data
    queryForm.pageNo = 1
    this.setData({
      status: 'loading',
      tableData: [],
      queryForm
    })
    this.fetchData()
  },
  async fetchData() {
    this.setData({
      status: 'loading'
    })
    const { queryForm, tableData } = this.data
    const data = await doList(queryForm)
    let newData = []
    data.list.map((el: any) => {
      if (!queryForm.destArea) {
        el.destArea = ''
      }
      if (el.pageViewTime && el.shortMessageTime) {
        const time1 = new Date(el.pageViewTime.replace(/-/g, '/')).getTime()
        const time2 = new Date(el.shortMessageTime.replace(/-/g, '/')).getTime()
        if (time1 > time2) {
          el.lastText = timeFrom(time1, false) + '有人浏览过此公司'
          el.lastType = 'view'
        } else {
          el.lastText = timeFrom(time2, false) + '有电话打到此公司'
          el.lastType = 'phone'
        }
      } else if (el.pageViewTime) {
        el.lastText = timeFrom(new Date(el.pageViewTime.replace(/-/g, '/')).getTime(), false) + '有人浏览过此公司'
        el.lastType = 'view'
      } else if (el.shortMessageTime) {
        el.lastText = timeFrom(new Date(el.shortMessageTime.replace(/-/g, '/')).getTime(), false) + '有电话打到此公司'
        el.lastType = 'phone'
      } else {
        el.lastText = '暂无电话打到此公司'
        el.lastType = 'phone'
      }
      return el
    })
    if (queryForm.pageNo === 1) {
      newData = data.list
    } else {
      newData = [...tableData, ...data.list]
    }
    queryForm.pageNo++
    this.setData({
      tableData: newData,
      queryForm,
      status: queryForm.pageSize === data.list.length ? 'loadmore' : 'nomore'
    })
    if (isRefresh) {
      wx.stopPullDownRefresh();
    }
  },
  /**
   * 生命周期函数--监听页面加载
   */
  onLoad(this: any, option: any) {
    this.storeBinding = createStoreBindings(this, {
      store,
      fields: {
        cityName: 'getCityName',
        cityCode: 'getCityCode',
        recordState: 'getRecordState',
        searchInfo: 'getSearchInfo',
      },
      actions: ['setCityArr', 'initMusic', 'setSearch']
    });
    watch.setWatcher(this);
    const item: {
      star: string
      end: string
    } = JSON.parse(decodeURIComponent(option.city));
    const starArr = item.star.split('-')
    const endArr = item.end.split('-')
    if (['北京', '重庆', '天津', '上海'].includes(starArr[0])) {
      starArr.splice(1, 1, starArr[0])
    }
    if (['北京', '重庆', '天津', '上海'].includes(endArr[0])) {
      endArr.splice(1, 1, endArr[0])
    }

    const { queryForm } = this.data
    if (starArr.length >= 1) {
      queryForm.sourceProvince = starArr[0]
    }
    if (starArr.length >= 2) {
      queryForm.sourceCity = starArr[1]
    }
    if (starArr.length >= 3) {
      queryForm.sourceArea = starArr[2]
    }
    if (endArr.length >= 1) {
      queryForm.destProvince = endArr[0]
    }
    if (endArr.length >= 2) {
      queryForm.destCity = endArr[1]
    }
    if (endArr.length >= 3) {
      queryForm.destArea = endArr[2]
    }
    this.setData({
      queryForm
    })
    this.setTitle()
    this.refres()
  },

  /**
   * 生命周期函数--监听页面初次渲染完成
   */
  onReady(this: any) {
    this.dialog = this.selectComponent("#dialog");
  },

  /**
   * 生命周期函数--监听页面显示
   */
  onShow() {

  },

  /**
   * 生命周期函数--监听页面隐藏
   */
  onHide() {

  },

  /**
   * 生命周期函数--监听页面卸载
   */
  onUnload() {

  },

  /**
   * 页面相关事件处理函数--监听用户下拉动作
   */
  onPullDownRefresh() {
    isRefresh = true
    const { queryForm } = this.data
    queryForm.pageNo = 1
    this.setData({
      status: 'loading',
      tableData: [],
      queryForm
    })
    this.fetchData()
  },

  /**
   * 页面上拉触底事件的处理函数
   */
  onReachBottom() {
    if (this.data.status == 'nomore') return
    this.fetchData()
  },

  /**
   * 用户点击右上角分享
   */
  onShareAppMessage() {

  },
  watch: {
    searchInfo: function (e: any) {
      const pages = getCurrentPages()
      if (e.star && pages.length > 0) {
        const path = pages[pages.length - 1].route
        if (path === 'pages/search/result') {
          this.searchChange(e)
        }
      }
    },
  }
})